package de.tabreaderandroid.tabreader.activities;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import de.tabreaderandroid.tabreader.R;
import de.tabreaderandroid.tabreader.model.TabFile;
import de.tabreaderandroid.tabreader.utils.InvalidTabFormatException;
import de.tabreaderandroid.tabreader.utils.TabFileUtils;

/**
 * This activity is responsible for showing the actual tab.
 * 
 * @author André Stannek
 * 
 */
public class TabViewActivity extends Activity {

	private TabFile tab;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tab_view);

		if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
				"screen_awake", true)) {
			getWindow()
					.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}

		EditText tabText = (EditText) findViewById(R.id.tab_text);
		try {
			tab = TabFileUtils.parseTabFile(getIntent().getExtras().getString(
					"filePath"));
			tabText.setText(tab.getOriginString(), BufferType.SPANNABLE);
		} catch (InvalidTabFormatException e) {
			Toast.makeText(getBaseContext(),
					getResources().getString(R.string.tab_parsing_error),
					Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);

		EditText tabText = (EditText) findViewById(R.id.tab_text);
		int width = tabText.getWidth();
		int maxCharWidth = tabText.getPaint().breakText(tab.getOriginString(),
				0, tab.getOriginString().length(), true, width, null);
		try {
			tabText.setText(TabFileUtils.getSpans(tab, maxCharWidth),
					BufferType.SPANNABLE);
		} catch (InvalidTabFormatException e) {
			Toast.makeText(getBaseContext(),
					getResources().getString(R.string.tab_display_error),
					Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.tab_view, menu);
		return true;
	}

	@Override
	public void onDestroy() {
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		super.onDestroy();
	}
}
